import aiohttp
import asyncio
import json
from datetime import datetime
from config import ZHUQUE_COOKIE, ZHUQUE_CSRF

#  配置区，运行前填好配置
cookie_headers = {
    "Cookie": ZHUQUE_COOKIE,
    "X-Csrf-Token": ZHUQUE_CSRF,
}

retry_times = 0
# info_counts = {item: 0 for item in prizes3.keys()}

url = "https://zhuque.in/api/gaming/listBet?tab=game"

setmmade = "list"


async def getgamelist(commade):
    global retry_times
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=cookie_headers) as response:
                re_message = ""
                if response.status == 200:
                    retry_times = 0
                    json_response = await response.json()
                    if json_response:
                        game_rows = json_response.get("data", {}).get("rows", [])
                        game_number = json_response.get("data", {}).get("total")
                        if commade == "list":
                            for sublist in game_rows[::-1]:
                                gameID = sublist["id"]
                                gameteam = ""
                                if len(sublist["info"]) == 2:
                                    gameteam = (
                                        f"{sublist['info'][0]} vs {sublist['info'][1]}"
                                    )
                                else:
                                    gameteam = " 、".join(
                                        team for team in sublist["info"]
                                    )
                                # gameteam2 = sublist["info"][1]
                                gametime = datetime.fromtimestamp(sublist["end_time"])
                                gametime1 = gametime.strftime("%Y-%m-%d %H:%M")
                                gametitle = sublist["title"]
                                if sublist["_status"] == 2:
                                    gameOdds = f"{float(100) / float(sublist['_status']['rate0']):.2f} : {float(100)  / float(sublist['_status']['rate1']):.2f}"
                                else:
                                    gameOdds = " : ".join(
                                        f"{float(100) / float(sublist['_status'][f'rate{i}']):.2f}"
                                        for i in range(len(sublist["_status"]) // 2)
                                    )
                                sum_bonus = sublist["_status"]["sum"]

                                re_message += f"\n\n比赛项目:{gametitle} \n\n   比赛ID:{gameID} 下注:{gameteam} 时间:{gametime1} 赔率:{gameOdds}  总下注金额:{sum_bonus}"
                        else:
                            if commade:
                                for row in game_rows:
                                    if row["id"] == commade:
                                        game_info = row["info"]
                                        re_message = game_info

                else:
                    print(f"Request failed with status {response.status}")
                    re_message = ""
                return re_message
    except aiohttp.ClientError as e:
        if retry_times < 10:
            print(f"Client error: {e}")
            retry_times += 1
            await asyncio.sleep(5)
            return await getgamelist
    except Exception as e:
        print(f"An error occurred: {e}")
        return None


async def main(commade):
    result_message = await getgamelist(commade)
    print(result_message)
    return result_message


# 运行主函数
if __name__ == "__main__":
    asyncio.run(main(setmmade))
